/*
   Mischevious window rearranger
   Created by Randall Maas, 2009
   Copyright (c) 2008-2009, Randall Maas
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:

   Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.

   Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

   Neither the name of Blackwood Designs, LLC nor the names of its contributors
   may be used to endorse or promote products derived from this software without
   specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
   THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System . Threading;
using System . Windows . Forms;
using System . Drawing ;
using System . Diagnostics;
using System . Reflection;
using NAudio . Wave;

static partial class Program
{
   /// <summary>
   /// Name of the application / window to search for
   /// </summary>
   static string AppName;

   /// <summary>
   /// Window handle or process id to search for
   /// </summary>
   static IntPtr AppId;

   /// <summary>
   /// An internal variable used to signal when we should stop or exit
   /// </summary>
   static volatile int Shutdown = 0;

   /// <summary>
   /// Window that receives the hot key events
   /// </summary>
   static HotKeyWindow HKW;

   /// <summary>
   /// Window that shakes the screen
   /// </summary>
   static ScrShake ScreenShaker;

   static bool Aggressive = false;
   static Point Force = Point . Empty;
   static double ShakeCoef = 2;
   static double AngleCoef = 0.1;

   [STAThread]
   static void Main(string[] Args)
   {
      // Check the arguments
      CmdLine(Args);

      // If the application is supposed to exit
      if (0 != Shutdown)
        return ;

      bool onlyInstance = false;
      Mutex mutex = new Mutex(true, Assembly.GetExecutingAssembly() . FullName, out onlyInstance);
      if (!onlyInstance)
        return;

      Application . EnableVisualStyles();
      Application . SetCompatibleTextRenderingDefault(false);

      BuildSuffixTree();

      WaveIn[] AudIns=null;

      // Bind hotkey
      try {
         using(HKW     = new HotKeyWindow())
         {
         // Register to get the Ctrl+F2 key press
         HKW . RegisterHotKey(Keys . F2 | Keys . Control,
           delegate (object sender, KeyEventArgs e)
           {
              Interlocked . Exchange(ref Shutdown, 1);
           });

         // Find window of the app we're going to test
         ISendPort Port = Win32 . CurrentFocusSendPort;
         int CntDown = 200;
         FindWins();

         // Next start up the Microphone to capture the frustration that fuels a gremlin
         AudIns = StartMics();

         ScreenShaker = new ScrShake(ShakeCoef, AngleCoef);

         // Sleep for a moment to let things stabilize
         Thread . Sleep(500);
         Console . WriteLine("Press Ctrl+F2 to stop.");

         // Randomly send events
         int State = 0;
         while (0 == Shutdown)
         {
            // Do some lovely events
            Application . DoEvents();
            Force . X = 0; Force . Y = 0;
            Thread . Sleep (20);
            // Periodically rescan the number of windows and their bounds
            if (--CntDown <= 0)
              {
                 CntDown = 200;
                 FindWins();
              }

            // Check for a kick from the sound system
            if (0 != AudioTrigger)
              {
                 Interlocked . Exchange(ref AudioTrigger, 0);
                 if (Aggressive)
                   {
                      Force . X = 0;
                      Force . Y = 20000;
                      UpdateMotion(Force);
                   }
                 ScreenShaker . Screens();
                 continue;
              }

            // If the user isn't idle, we should do be patient
            uint LastTime = Win32 . LastInputTime();
            if ((uint) Environment.TickCount < IdleTimeTrigger + LastTime)
              {
                 State = 0;
                 UpdateMotion(Force);
                 continue;
              }
             else if (0 == State)
              {
                 State = 1;
                 Force . X = Rnd . Next(-100, 100)*200000;
                 Force . Y = Rnd . Next(-100, 100)*200000;
              }


            // Send random events
            SendRandomEvents(Port, Force);
         }
      }
      }
      finally
      {
         StopMics(AudIns);
         // Restore all of the windows !
         foreach (WinMass W in Ws . Values)
          W . Dispose();

      // This is importat
      GC . KeepAlive(mutex);
      mutex . ReleaseMutex();
      }
   }

   static int IdleTimeTrigger = 2*60*1000;
   const int SleepDuration = 20;
}

